#include "DesaturateFilter.h"

DesaturateFilter::DesaturateFilter(void)
{
}

DesaturateFilter::~DesaturateFilter(void)
{
}
bool DesaturateFilter::apply(Image& pImage)
{
	const int nmbThreads = 4;
	int h = pImage.getHeight();
	int w = pImage.getWidth();

	threadDimension tiles[nmbThreads];
	HANDLE threads[nmbThreads];

	for(int i = 0 ; i <nmbThreads; i++)
	{
		tiles[i].width = w;
		tiles[i].height = h/nmbThreads*(i+1);
		tiles[i].xStartPoint = 0;
		tiles[i].yStartPoint = h/nmbThreads*i;;
		tiles[i].pImage = &pImage;
		threads[i] =  CreateThread(NULL, 0, &threadFilter, tiles + i, 0, NULL);

	}
	

	for(int i = 0 ; i <nmbThreads; i++)
	{
		WaitForSingleObject(threads[i], INFINITE);
		CloseHandle(threads[i]);
		
	}


	//for(int i = 0; i< h; i++)
	//{
	//	for(int j = 0; j< w; j++)
	//	{
	//		Image::Color currentPixel = pImage.getValue(j, i);

	//		float average = ( currentPixel.r*0.3 + currentPixel.g*0.5 + currentPixel.b*0.2 );

	//		currentPixel.r = average;
	//		currentPixel.g = average;
	//		currentPixel.b = average;

	//		pImage.setValue(j,i, currentPixel);
	//	}
	//}


	//threadDimension dimension1 = {w, h/2, 0,0, &pImage};
	//HANDLE threadHandle1 =  CreateThread(NULL, 0, &threadFilter, &dimension2, 0, NULL);

	//WaitForSingleObject(threadHandle1, INFINITE);
	//CloseHandle(threadHandle1);

	//threadDimension dimension2 = {w, h, h/2,0, &pImage};
	//HANDLE threadHandle2 =  CreateThread(NULL, 0, &threadFilter, &dimension2, 0, NULL);

	//WaitForSingleObject(threadHandle22, INFINITE);
	//CloseHandle(threadHandle2);
	return true;
}
DWORD WINAPI DesaturateFilter::threadFilter(void* params)
{
	threadDimension* dim = (threadDimension*)params;

	for(int i = dim->yStartPoint; i< dim->height; i++)
	{
		for(int j = dim->xStartPoint; j< dim->width; j++)
		{
			Image::Color currentPixel = dim->pImage->getValue(j, i);

			float average = ( currentPixel.r*0.3 + currentPixel.g*0.5 + currentPixel.b*0.2 );

			currentPixel.r = average;
			currentPixel.g = average;
			currentPixel.b = average;

			dim->pImage->setValue(j,i, currentPixel);
		}
	}

	return 0;
}
